<?php

namespace App\Http\Controllers\Admin\Personnel;

use App\Http\Controllers\Controller;
use App\Http\Requests\DeptRequest;
use Illuminate\Http\Request;
use App\Models\DeptModel;
use App\Models\StaffModel;

class Dept extends Controller
{

    use DeptRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = DeptModel::query()->with('create_admin')->with('staff');

        if($name) {
            $query->where('name', 'like', "%{$name}%");
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->orderBy('id','desc')
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin->staff->name ?? ''
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $dept = new DeptModel();
        $dept->name = $params['name'];
        $dept->created_admin_id = $auth->id;
        $dept->save();

        return $this->success();
    }

    public function update(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $dept = DeptModel::find($params['id']);
        if(!$dept) {
            return $this->error('记录不存在');
        }

        $dept->name = $params['name'];
        $dept->created_admin_id = $auth->id;
        $dept->save();

        return $this->success();
    }

    public function delete(Request $request, int $id){
        $dept = DeptModel::find($id);
        if(!$dept) {
            return $this->error('记录未找到');
        }
        $dept->delete();
        return $this->success();
    }

}
